import 'package:enterprise_v6_app/app/components/custom_refresh.dart';
import 'package:enterprise_v6_app/app/components/special_operation/custom_select_function.dart';
import 'package:enterprise_v6_app/app/components/toast_widget.dart';
import 'package:enterprise_v6_app/app/core/core.dart';
import 'package:enterprise_v6_app/app/core/http/http.dart';
import 'package:enterprise_v6_app/app/core/utils/interface.dart';
import 'package:enterprise_v6_app/app/data/entities/application/education/couser_center/get_detail_by_id_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/application/education/couser_center/list_question_by_book_id_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/application/education/demand_research/education_survey_list_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/application/education/demand_research/get_setting_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/application/get_dict_all_entity.dart';
import 'package:enterprise_v6_app/app/modules/application/education/quiz/model.dart';
import 'package:enterprise_v6_app/router/app_pages.dart';

///需求调研（进行中）
class AllIngResearchController extends GetxController {
  ///查询调研问卷题列表
  List<ListQuestionByBookIdEntity>? listSurveyQuestion = [];

  /// 筛选右侧栏控制Key
  final riskRightScaffoldKey = GlobalKey<ScaffoldState>();

  /// 列表刷新key
  final GlobalKey<CustomEasyRefreshListState> globalKey = GlobalKey();

  /// 搜索条件
  String? searchX;

  /// 开始时间
  String startDate = '';

  /// 结束时间
  String endDate = '';

  /// 获取调查问卷时长
  GetSettingEntity? getSettingEntity;

  String? workKindNameBack = '请选择';
  String? workKind = '';

  /// 调研类型 1调研测验 2调查问卷
   List<GetDictAllEntity> researchType = [];
  @override
  void onInit() {
    super.onInit();
    //调研类型 	0：问卷 1：测验
    initResearchType();
    //查询企业调研临期时间(调查问卷时长)
    getTextBookSetting();
  }

  ///查询企业调研临期时间(调查问卷时长)
  void getTextBookSetting() async {
    final res = await HttpUtil()
        .generatePostRequest<GetSettingEntity>(
          Interface.getSetting,
        )
        .execute();
    res.onSuccess((result) {
      if (result.data != null) {
        getSettingEntity = result.data!;
      }
    });
  }

  /// 获取数据
  Future<List<EducationSurveyListEntity>> educationSurveyList(int index, int size, {String? search}) async {
    final res = await HttpUtil().generateGetRequest<List<EducationSurveyListEntity>>(
      Interface.educationSurveyList,
      queryParameters: {
        'pageNum': index,
        'pageSize': size,
        'surveyStatus': 1, //调研状态 	surveyStatus状态 0：待提交 1：进行中 2：已结束
        'surveyEndDate': startDate, //开始时间
        'surveyStartDate': endDate, //结束时间
        'surveyType': workKind, //	少了调研类型
        'surveyName': searchX, //模糊查询
        'type': 1, //	是否待我填写的 1：是
        'isApp': 1, //	是否是app 1：是
      },
    ).execute();
    List<EducationSurveyListEntity>? list = [];
    res.onSuccess((result) {
      if (result.data != null) {
        list = result.data;
      }
    });
    return list!;
  }

  ///筛选按钮
  void onFilterButtonPressed() {
    riskRightScaffoldKey.currentState?.openEndDrawer();
  }

  /// 重置
  void reset() {
    startDate = '';
    endDate = '';
    workKind = '';
    workKindNameBack = '请选择';
    globalKey.currentState!.onRefresh();
    update();
  }

  /// 确定
  void confirm() {
    Get.back();
    globalKey.currentState!.onRefresh();
    update();
  }

  GetDictAllEntity? dictEntity2;


  /// 状态
  void selectHiddenDangerInvestigationTaskWorkKindType() {
    CustomSelectFunction.selectMultipleBottomSheet<GetDictAllEntity>(
      title: '调研类型',
      dataList: researchType,
      checkedList: [dictEntity2 ?? GetDictAllEntity()],
      isMultiple: false,
      onCallBack: (value) {
        dictEntity2 = value[0];
        workKind = value[0].getId();
        workKindNameBack = value[0].getShowName().isEmpty ? '请选择' : value[0].getShowName();
        update();
      },
    );
  }

  void refreshPage() {
    globalKey.currentState?.onRefresh();
  }

  ///进入调查问卷界面
  void inputClickPage(EducationSurveyListEntity item) {
    //我的调研
    //调研类型 0：问卷
    if (item.surveyType == 0) {
      Get.toNamed(AppRoutes.questionnaireDetailPage, arguments: {'id': item.id ?? ''}); //需求调研ID
    } else {
      //调研类型 1：测验
      //根据课程查询试题列表
      getListSurveyQuestion(item.id);
    }
  }

  ///查询调研问卷题列表
  void getListSurveyQuestion(String? id) async {
    final res = await HttpUtil().generateGetRequest<List<ListQuestionByBookIdEntity>>(
      Interface.listSurveyQuestion,
      queryParameters: {
        'id': id,
      },
    ).execute();
    res.onSuccess((result) {
      if (result.data != null) {
        listSurveyQuestion = result.data!;
        //开始做题
        startDoingQuestions(id);
      }
    });
  }

  ///开始做题
  Future<void> startDoingQuestions(String? id) async {
    final List<QuizTopic> topicsX = [];
    for (var listEntity in listSurveyQuestion!) {
      List<int>? answersX = [];
      final List<String> optionsX = [];
      if (listEntity.optionA != null) {
        optionsX.add('${listEntity.optionA}');
      }
      if (listEntity.optionB != null) {
        optionsX.add('${listEntity.optionB}');
      }
      if (listEntity.optionC != null) {
        optionsX.add('${listEntity.optionC}');
      }
      if (listEntity.optionD != null) {
        optionsX.add('${listEntity.optionD}');
      }
      //转码-对应的65 得到0的角标 A(65)-65=0
      answersX = listEntity.questionValidity?.split(';').map((e) => e.codeUnitAt(0) - 65).toList();
      topicsX.add(QuizTopic(
        id: listEntity.id ?? '',
        question: '${listEntity.questionMain}',
        answers: answersX,
        options: optionsX,
        score: listEntity.score ?? 0,
      ));
    }
    if (topicsX.isEmpty) {
      AppToast.showWarning('没有题目~');
      return;
    }

    final res = await HttpUtil().generateGetRequest<GetDetailByIdEntity>(
      Interface.getDetailById,
      queryParameters: {
        'id': id,
      },
    ).execute();
    res.onSuccess((result) {
      if (result.data == null) {
        AppToast.showError('get survey failed');
        return;
      }

      Get.toNamed(AppRoutes.quizPage,
          arguments: QuizConfig(
            type: QuizType.demandTest,
            topics: topicsX,
            surveys: result.data,
            leftSeconds: getSettingEntity?.value != null ? getSettingEntity!.value! * 60 : 60,
          ));
    });
  }

  ///进入详情
  void onClickButtonPressed(EducationSurveyListEntity item) {
    Get.toNamed(AppRoutes.meDemandResearchDetailPage, arguments: {
      'id': item.id ?? '',
      //是否是 true 调查问卷  false 调研测验
      'isText': item.surveyType == 0 ? true : false,
      'isShow': false, //是否显示调研结果（只有进行中才显示）
    });
  }

  void initResearchType() {
    researchType.clear();
    final GetDictAllEntity getDictAllEntity4 = GetDictAllEntity();
    getDictAllEntity4.id = '0';
    getDictAllEntity4.dictionaryLabel = '问卷';
    researchType.add(getDictAllEntity4);

    final GetDictAllEntity getDictAllEntity5 = GetDictAllEntity();
    getDictAllEntity5.id = '1';
    getDictAllEntity5.dictionaryLabel = '测验';
    researchType.add(getDictAllEntity5);
  }
}
